<template>
  <el-table :id="id" border ref="table" @selection-change="handleSelectionChange" :data="list" min-height="200"
            :height="tableHeight" :size="size" style="width: 100%;">
    <el-table-column v-if="selection" :type="selection ? 'selection' : ''" width="50" align="center">
    </el-table-column>
    <el-table-column v-if="showIndex" label="序号" type="index" width="50" align="center">
    </el-table-column>
    <el-table-column v-for="(item, index) in columns" :key="index" :prop="item.prop" :label="item.title"
                     :width="item.width" :align="item.align" :sortable="item.sortable">
      <template slot-scope="scope">
        <ex-slot v-if="item.render" :render="item.render" :row="scope.row" :index="scope.$index" :column="item"/>
        <span v-else>{{ scope.row[item.prop] != null ? scope.row[item.prop] : "-" }}</span>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
  // 自定义内容的组件
  var exSlot = {
    functional: true,
    props: {
      row: Object,
      render: Function,
      index: Number,
      column: {
        type: Object,
        default: null
      }
    },
    render: (h, data) => {
      const params = {
        row: data.props.row,
        index: data.props.index
      }
      if (data.props.column) params.column = data.props.column
      return data.props.render(h, params)
    }
  }
  export default {
    components: {
      exSlot
    },
    props: {
      id: String,
      columns: {
        type: Array,
        default: () => []
      },
      list: {
        type: Array,
        default: () => []
      },
      selection: {
        type: Boolean,
        default: () => false
      },
      showIndex: {
        type: Boolean,
        default: () => false
      },
      size: {
        type: String,
        default: () => ""
      },
      defaultList: {
        type: Array,
        default: () => []
      },
      tableHeight: {
        type: String,
        default: () => "100%"
      }
    },
    mounted() {

    },
    data() {
      return {
        tableData: []
      }
    },
    // 存放方法事件 - 会在数据变化时被调用
    methods: {
      handleSelectionChange(e) {
        this.$emit("handleSelectionChange", e)
      },
      selectedData() {
        this.$nextTick(function() {
          if (this.defaultList.length != 0) {
            let rows = []
            for (let m = 0; m < this.defaultList.length; m++) {
              for (let n = 0; n < this.list.length; n++) {
                if (this.defaultList[m].id == this.list[n].id) {
                  rows.push(this.list[n])
                }
              }
            }
            rows.forEach(row => {
              this.$refs.table.toggleRowSelection(row)
            })
          }
        })
      }
    }

  }
</script>

<style lang="scss" scoped></style>
